using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
using System.IO;

namespace IESDK
{
    public class IESDKWindowTools : EditorWindow
    {


        [MenuItem("IESDK/清除存储数据")]
        public static void ClearSave()

        {
            PlayerPrefs.DeleteAll();
        }
        [MenuItem("IESDK/清理所有预制体里脚本丢失的引用")]
        private static void ClearPrefabsMissingScripts()
        {
            List<GameObject> prefabs = GetAllPrefabs();
            for (var i = 0; i < prefabs.Count; i++)
            {
                FindInGO(prefabs[i]);
                EditorUtility.ClearProgressBar();
                PrefabUtility.SavePrefabAsset(prefabs[i]);
            }
        }

        [MenuItem("IESDK/清理当前场景丢失的引用")]
        private static void StartRemoveMissingScripts()
        {
            Scene currentScene = EditorSceneManager.GetActiveScene();
            GameObject[] _go = Resources.FindObjectsOfTypeAll<GameObject>();
            int _count = _go.Length;
            int _cur = 0;

            foreach (GameObject _gameObject in _go)
            {
                FindInGO(_gameObject);

                _cur++;

                EditorUtility.DisplayCancelableProgressBar("Processing...", $"{(_cur + 1)}/{_count}", (float)_cur / _count);
            }

            EditorUtility.ClearProgressBar();
        }
   

        [MenuItem("IESDK/清理选中GameObject中丢失的引用.")]
        private static void FindInSelected()
        {
            GameObject[] _go = Selection.gameObjects;

            int _count = _go.Length;
            int _cur = 0;

            foreach (GameObject _gameObject in _go)
            {
                FindInGO(_gameObject);

                _cur++;

                EditorUtility.DisplayCancelableProgressBar("Processing...", $"{(_cur + 1)}/{_count}", (float)_cur / _count);
            }

            EditorUtility.ClearProgressBar();
        }
        [MenuItem("IESDK/导出选择的图集图片")]
        private static void ExportSprite()
        {
            Texture2D image = Selection.activeObject as Texture2D;//获取对象

            if (image != null)
            {
                string tDirName = AssetDatabase.GetAssetPath(image).Replace(image.name + ".png", image.name + "") + @"/";
                tDirName = tDirName.Replace(@"Assets/", @"TexturePacker/");    //输出路径
                string path = Path.GetDirectoryName(AssetDatabase.GetAssetPath(image)) + "/" + image.name + ".png";//图片路径名称

                if (Directory.Exists(tDirName) == false)
                {
                    Directory.CreateDirectory(tDirName);
                }

                TextureImporter texImp = AssetImporter.GetAtPath(path) as TextureImporter;

                foreach (SpriteMetaData metaData in texImp.spritesheet) //遍历小图集
                {
                    Texture2D myimage = new Texture2D((int)metaData.rect.width, (int)metaData.rect.height);
                    for (int y = (int)metaData.rect.y; y < metaData.rect.y + metaData.rect.height; y++)//Y轴像素
                    {
                        for (int x = (int)metaData.rect.x; x < metaData.rect.x + metaData.rect.width; x++)
                            myimage.SetPixel(x - (int)metaData.rect.x, y - (int)metaData.rect.y, image.GetPixel(x, y));
                    }

                    //转换纹理到EncodeToPNG兼容格式
                    if (myimage.format != TextureFormat.ARGB32 && myimage.format != TextureFormat.RGB24)
                    {
                        Texture2D newTexture = new Texture2D(myimage.width, myimage.height);
                        newTexture.SetPixels(myimage.GetPixels(0), 0);
                        myimage = newTexture;
                    }
                    var pngData = myimage.EncodeToPNG();
                    File.WriteAllBytes(tDirName + "/" + metaData.name + ".png", pngData);
                }

                Debug.LogError("export " + image.name + " sprite finished");
            }
        }
        private static void FindAll()
        {
            string[] _assetsPaths = AssetDatabase.GetAllAssetPaths();

            int _count = _assetsPaths.Length;
            int _cur = 0;

            foreach (string _assetPath in _assetsPaths)
            {
                Object[] _objects = LoadAllAssetsAtPath(_assetPath);

                foreach (Object _o in _objects)
                {
                    if (_o != null)
                    {
                        if (_o is GameObject _gameObject)
                        {
                            FindInGO(_gameObject);
                        }
                    }
                }

                _cur++;
                EditorUtility.DisplayCancelableProgressBar("Processing...", $"{(_cur + 1)}/{_count}", (float)_cur / _count);
            }
            EditorUtility.ClearProgressBar();
        }

        public static Object[] LoadAllAssetsAtPath(string assetPath)
        {
            return typeof(SceneAsset) == AssetDatabase.GetMainAssetTypeAtPath(assetPath) ?
                new[] { AssetDatabase.LoadMainAssetAtPath(assetPath) } :
                AssetDatabase.LoadAllAssetsAtPath(assetPath);
        }

        private static void FindInGO(GameObject _gameObject)
        {
            Component[] _components = _gameObject.GetComponents<Component>();

            bool _flag = false;

            for (int i = 0; i < _components.Length; i++)
            {
                if (_components[i] == null)
                {
                    _flag = true;

                    break;
                }
            }

            if (_flag)
            {
                RemoveRecursively(_gameObject);
            }

            foreach (Transform _transform in _gameObject.transform)
            {
                FindInGO(_transform.gameObject);
            }
        }

        private static void RemoveRecursively(GameObject _gameObject)
        {
            GameObjectUtility.RemoveMonoBehavioursWithMissingScript(_gameObject);

            foreach (Transform _transform in _gameObject.transform)
            {
                RemoveRecursively(_transform.gameObject);
            }
        }
        private static List<GameObject> GetAllPrefabs()
        {
            List<GameObject> prefabs = new List<GameObject>();
            //var resourcesPath = Application.dataPath;
            var resourcesPath = Application.dataPath + "/Resources/levels";
            var absolutePaths = System.IO.Directory.GetFiles(resourcesPath, "*.prefab", System.IO.SearchOption.AllDirectories);
            for (int i = 0; i < absolutePaths.Length; i++)
            {
                EditorUtility.DisplayProgressBar("获取预制体……", "获取预制体中……", (float)i / absolutePaths.Length);
                string path = "Assets/Resources/levels" + absolutePaths[i].Remove(0, resourcesPath.Length);
                path = path.Replace("\\", "/");
                GameObject prefab = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;
                if (prefab != null)
                {
                    prefabs.Add(prefab);
                }
                else
                    Debug.Log("预制体不存在！" + path);
            }
            EditorUtility.ClearProgressBar();
            return prefabs;
        }
        public static bool AA()
        {
            if (AssetDatabase.FindAssets("TextMesh Pro").Length > 0)
            {
                Debug.Log("TextMeshPro is available.");
                return true;
                // 在这里你可以使用TextMeshPro库
                // using TMPro;
            }
            else
            {
                Debug.Log("TextMeshPro is not available.");
                return false;
            }
        }
    }
}
